package com.sirui.mongo.web;

import com.sirui.mongo.file.MongoGridFSService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/img")
public class ImgController {

    @Autowired
    MongoGridFSService mongoGridFSService;

    @RequestMapping("getImg/{objId}/{index}")
    public void getImg(HttpServletResponse response, @PathVariable Integer objId, @PathVariable Integer index) throws IOException {
        Criteria criteria = new Criteria();
        criteria.and("metadata.objId").is(objId);
        criteria.and("metadata.index").is(index);
        InputStream inputStream = mongoGridFSService.readFromGridFSByCriteria(criteria);
        mongoGridFSService.downFile(criteria);

        //BufferedImage bufferedImage = ImageIO.read(inputStream);
        //ImageIO.write(bufferedImage, "jpg", response.getOutputStream());

        response.setContentType("image/jpeg");
        byte[] bytes = IOUtils.toByteArray(inputStream);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();

        inputStream.close();
    }
}
